<?php
/** UnivIS update script
 * Tests connection to Univis-Server
 * Downloads content from UnivIS via PRG interface in XML
 * Validates XML files
 * finally parse the content and stores
 * it into a mysql database
 */

require_once t3lib_extMgm::extPath('univis2typo3').'/mod1/parser/class.parser.php';
require_once t3lib_extMgm::extPath('univis2typo3').'/mod1/parser/debug.php';
require_once t3lib_extMgm::extPath('univis2typo3').'/mod1/parser/error.php';
require_once t3lib_extMgm::extPath('univis2typo3').'/mod1/parser/modules/generic_module.php';
require_once t3lib_extMgm::extPath('univis2typo3').'/mod1/parser/modules/departments_module.php';
require_once t3lib_extMgm::extPath('univis2typo3').'/mod1/parser/modules/lectures_module.php';


$goForUpdate = true;

// Validate XML File
function validateXML($xmlToValidate)
{
	$xmlParser= xml_parser_create();
	if(!xml_parse($xmlParser, $xmlToValidate, true))
	{
		U2T3_DEBUG("ERROR occurred\n");
		if(xml_get_error_code($xmlParser))
		{
			U2T3_ERROR(xml_error_string(xml_get_error_code($xmlParser))."\n");
		}
		return false;
	}
	return true;
}

function univisOnlineTest($conf)
{
	ini_set('max_execution_time', 300);
	U2T3_DEBUG("> Testing if UnivIS server is reachable.\n");
	U2T3_DEBUG("  Try to open socket port 80 of the UnivIS server: ".$conf['univis']['server']." \n");
	$fp = @fsockopen($conf['univis']['server'], 80, $errno, $errstring, 5);
	if(!$fp)
	{
		U2T3_ERROR("  Could not connect to UnivIS server.\n");
		return false;
	} else {
		fclose($fp);
		switch ($errno) {
			case 0:
				U2T3_DEBUG("< UnivIS server reachable.\n");
				return true;
				break;
			case 110:
				U2T3_ERROR("  UnivIS connection timed out.\n");
				return false;
				break;
			case 111:
				U2T3_ERROR("  Server seems to be offline.\n");
				return false;
				break;
			default:
				U2T3_ERROR("  Unknown error: ($errno: $errstring).\n");
				return false;
		}
	}
}



function updateFromUnivis($conf){

	//Count modules to import
	$moduleCount = 0;
	foreach ($conf['univis']['modules'] as $module => $import)
	{
		if (true === $import) $moduleCount++;
	}

	$nSubSteps = 1 + 3 * $moduleCount;

	$currentPercentage = $conf['ProgressBar']->getCurrentProgress();
	$maxPercentage = $conf['ProgressBar']->getCurrentStepEndProgress();
	$stepPercentage = (($maxPercentage - $currentPercentage)/ $nSubSteps);

	global $department_id;
	$department_id=$conf['univis']['department'];

	$conf['ProgressBar']->setUpdateInfo($department_id.': Checking if UnivIS is online.');

	if (false === univisOnlineTest($conf))
	{
		$goForUpdate = false;
	}

	$currentPercentage += $stepPercentage;
	$conf['ProgressBar']->setCurrentProgress($currentPercentage);
	// Import modules
	U2T3_DEBUG("Create tempory folder");
	t3lib_div::mkdir(PATH_site.'typo3temp/u2t3temp');

	U2T3_DEBUG("Downloading UnivIS XML files.\n");

	foreach ($conf['univis']['modules'] as $module => $import)
	{
		if (false === $import)
		{
			continue;
		}

		$moduleClass = ucfirst($module).'Module';
		if (!class_exists($moduleClass))
		{
			$moduleClass = 'GenericModule';
		}
		$moduleController = new $moduleClass($module);

		$conf['ProgressBar']->setUpdateInfo($department_id.': Downloading XML for module '.ucfirst($module) );

		do
		{
			$loop = false;
			$url = $moduleController->getUrl($conf['univis']);

			$rawxml = '';
			$xml = '';
			U2T3_DEBUG( '> Fetching '.ucfirst($module)." XML data from\n"
				    ."    {$url}\n");

			$rawxml = file_get_contents($url);

			// fix line breaks
			$rawxml = str_replace(array('&#x0A;', '&#x0D;'), array("\n", "\r"), $rawxml);
			// fix ligatures. the commented codes are not certain to be correct
			$xml = str_replace(array('&#x0B;', '&#x0C;'/*, '&#x0D;', '&#x0E;', '&#x0F;'*/), array('ff', 'fi'/*, 'fl', 'ffi', 'ffl'*/), $rawxml);

			unset($rawxml);
			$filename= str_replace($conf['univis']['prg_url'],'', $url);
			t3lib_div::writeFileToTypo3tempDir(PATH_site.'typo3temp/u2t3temp/'.$filename, $xml);

			$loop = $moduleController->hasMoreUrls();
		} while($loop);
		
		$currentPercentage += $stepPercentage;
		$conf['ProgressBar']->setCurrentProgress($currentPercentage);
	}

	// Validate XML Files
	U2T3_DEBUG("Validate XML Files\n");
	foreach ($conf['univis']['modules'] as $module => $import)
	{
		if (false === $import)
		{
			continue;
		}
		$moduleClass = ucfirst($module).'Module';
		U2T3_DEBUG("Loading moduleClass {$moduleClass}");
		if (!class_exists($moduleClass))
		{
			$moduleClass = 'GenericModule';
		}
		$moduleController = new $moduleClass($module);

		$conf['ProgressBar']->setUpdateInfo($department_id.': Validating XML for module '.ucfirst($module));

		do
		{
			$loop = false;
			$url = $moduleController->getUrl($conf['univis']);
			$filename = str_replace($conf['univis']['prg_url'], '', $url);
			U2T3_DEBUG("Reading file: ".PATH_site.'typo3temp/u2t3temp/'.$filename );
			$rawxml = file_get_contents(PATH_site.'typo3temp/u2t3temp/'.$filename);

			// Validate XML
			U2T3_DEBUG('> Validating XML: '.ucfirst($module)."\n");
			$rv = validateXML($rawxml);
			unset($rawxml);
			if(false === $rv)
			{
				U2T3_DEBUG("< XML Error\n");
				$goForUpdate = false;
				break;
			}
			U2T3_DEBUG("< XML Validated\n");
			$loop = $moduleController->hasMoreUrls();
		} while($loop);

		$currentPercentage += $stepPercentage;
		$conf['ProgressBar']->setCurrentProgress($currentPercentage);

	}


	// Parse XML Files
	U2T3_DEBUG("Parsing XML files\n");
	foreach ($conf['univis']['modules'] as $module => $import)
	{
		if (false === $import)
		{
			continue;
		}

		$moduleClass = ucfirst($module).'Module';
		if (!class_exists($moduleClass))
		{
			$moduleClass = 'GenericModule';
		}
		$moduleController = new $moduleClass($module);

		$conf['ProgressBar']->setUpdateInfo($department_id.': Parsing XML for module '.ucfirst($module));

		do
		{
			$loop = false;

			$url = $moduleController->getUrl($conf['univis']);
			$filename = str_replace($conf['univis']['prg_url'], '', $url);

			$rawxml = file_get_contents(PATH_site.'typo3temp/u2t3temp/'.$filename);

			// Load parser
			U2T3_DEBUG('> Parsing of '.ucfirst($module)."\n");
			$parserClass = 'UnivisParser';
			include_once 'parsers/univisparser.php';
			$parser = new $parserClass($module);
			$parser->department_id = $conf['univis']['department'];
			$parser->parse($rawxml);
			U2T3_DEBUG('< Parsing of '.ucfirst($module)." done.\n");

			$loop = $moduleController->hasMoreUrls();
		} while($loop);

		$currentPercentage += $stepPercentage;
		$conf['ProgressBar']->setCurrentProgress($currentPercentage);

	}

	U2T3_DEBUG("Deleting tempory folder");
	t3lib_div::rmdir(PATH_site.'typo3temp/u2t3temp', true);

}
?>
